/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.safetytask.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.emailandsms.SendEmail;
import com.koron.common.emailandsms.SendMsg;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.safetytask.domain.*;
import com.koron.safetytask.mapper.*;
import com.koron.safetytask.service.api.UserTaskService;
import com.koron.safetytask.utils.BusinessCode;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.web.org.mapper.StaffMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserTaskServiceImpl implements UserTaskService, AfterApprovalService {

    @Value("${app.appid}")
    private String appId;

    @Value("${flow_safe_task_tempKey}")
    private String userTaskTempKey;

    @Value("${flow_safe_task_set_code}")
    private String userTaskSetCode;

    @Value("${app.secret}")
    private String secret;
    private final static  Logger logger = LoggerFactory.getLogger(UserTaskServiceImpl.class);
    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private Util util;

    @Override
    public MessageBean<Integer> save(StaffBean user, UserTask userTask, Integer operatorType, MultipartFile[] files, String keepAttAddress, String delAttAddress) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        List<String> keepAttsList = new ArrayList<>();
        List<String> emailList = new ArrayList<>();
        List<String> phoneList = new ArrayList<>();
        try {
            if (StringUtils.isNotEmpty(keepAttAddress)) {
                String[] keepArrays = keepAttAddress.split("[,，]");
                for (String att : keepArrays) {
                    keepAttsList.add(att);
                }
            }
            UserTaskMapper taskMapper = factory.getMapper(UserTaskMapper.class);
            MessageMapper messageMapper = factory.getMapper(MessageMapper.class);
            if (StringUtils.isEmpty(userTask.getTaskName())) {
                msg.setCode(BusinessCode.TASK_EMPTY_TASKNAME.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_TASKNAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(userTask.getTaskDesc())) {
                msg.setCode(BusinessCode.TASK_EMPTY_TASKDESCRIPTION.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_TASKDESCRIPTION.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(userTask.getInitiatorCode())) {
                msg.setCode(BusinessCode.TASK_EMPTY_TASKINITIATORCODE.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_TASKINITIATORCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(userTask.getReceiverCode())) {
                msg.setCode(BusinessCode.TASK_EMPTY_TASKRECEIVERCODE.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_TASKRECEIVERCODE.getDescription());
                return msg;
            }
            //操作类型值不合法时，默认保存草稿操作
            if (operatorType==null||operatorType<0||operatorType>1) {
                operatorType=0;
            }
            InputStream[] inputStreams = null;
            if (null != files && files.length > 0) {
                inputStreams = new InputStream[files.length];
                int i = 0;
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepAttsList.add(url + "#" + file.getOriginalFilename());
                    inputStreams[i] = file.getInputStream();
                    i++;
                }
            }
            //处理执行人
            String[] receiverCodeArray = userTask.getReceiverCode().split("[,，]");
            List<String> receiverList = Arrays.asList(receiverCodeArray).stream().map(String::trim).collect(Collectors.toList());
            userTask.setReceiverCode(new Gson().toJson(receiverList));
            if (StringUtils.isNotEmpty(userTask.getReceiverName())) {
                String[] receiverNameArray = userTask.getReceiverName().split("[,，]");
                List<String> receiverNameList = Arrays.asList(receiverNameArray).stream().map(String::trim).collect(Collectors.toList());
                userTask.setReceiverName(new Gson().toJson(receiverNameList));
            }
            //处理抄送人
            List<String> copyList = new ArrayList<>();
            List<String> copyNameList = new ArrayList<>();
            if (StringUtils.isNotEmpty(userTask.getCopyPerson()) && StringUtils.isNotEmpty(userTask.getCopyPersonName())) {
                String[] copyArray = userTask.getCopyPerson().split("[,，]");
                String[] copyNameArray = userTask.getCopyPersonName().split("[，,]");
                copyList = Arrays.asList(copyArray).stream().map(String::trim).collect(Collectors.toList());
                copyNameList = Arrays.asList(copyNameArray).stream().map(String::trim).collect(Collectors.toList());
                //获取抄送人的电话和邮箱
                if (null != copyList && copyList.size() > 0) {
                    for (String copyCode : copyList) {
                        String code = copyCode.split("_")[0];
                        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(code, null).getData();
                        if (null != staffBeanList && staffBeanList.size() > 0) {
                            if (!emailList.contains(staffBeanList.get(0).getEmail())) {
                                emailList.add(staffBeanList.get(0).getEmail());
                            }
                            if (!phoneList.contains(staffBeanList.get(0).getMobile())) {
                                phoneList.add(staffBeanList.get(0).getMobile());
                            }
                        }
                    }
                }
                if (null != copyList && copyList.size() > 0 && null != copyNameList && copyNameList.size() > 0) {
                    userTask.setCopyPerson(new Gson().toJson(copyList));
                    userTask.setCopyPersonName(new Gson().toJson(copyNameList));
                }
            }

            Integer value = 0;
            if(operatorType==0){
                userTask.setState(3);
            }else{
                userTask.setState(0);
            }
            if(StringUtils.isEmpty(userTask.getId())){
                //新增操作
                userTask.setAddTime(userTask.getUpdateTime());
                userTask.setAddUser(userTask.getUpdateUser());
                userTask.setId(DefaultIdGenerator.getInstance().generateLongId());
                if (null != keepAttsList && keepAttsList.size() > 0) {
                    userTask.setTaskFile(new Gson().toJson(keepAttsList));
                }
                taskMapper.insert(userTask);
            }else{
                //修改操作
                UserTask entity = query(userTask.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getCode());
                    msg.setDescription(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getDescription());
                    return msg;
                }
                if(entity.getState()!=3){
                    msg.setCode(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getCode());
                    msg.setDescription("任务已经发布，无法修改");
                    return msg;
                }
                //先删除之前任务与用户之间的关系
                factory.getMapper(TaskUserRelationMapper.class).delete(userTask.getId());
                //修改任务信息
                taskMapper.update(userTask);
            }
            //判断是否任务提交操作
            if(operatorType==1){
                //提交操作，向任务执行人，抄送人等发送消息、邮件、短信等通知
                List<TaskUserRelation> relationList = new ArrayList<>();
                List<Message> messageList = new ArrayList<>();
                for (String receiverCode : receiverList) {
                    TaskUserRelation relation = new TaskUserRelation();
                    relation.setId(DefaultIdGenerator.getInstance().generateLongId());
                    relation.setReceiverCode(receiverCode);
                    relation.setIsFinish(0);
                    relation.setTaskId(userTask.getId());
                    relation.setAddTime(userTask.getUpdateTime());
                    relation.setUpdateTime(userTask.getUpdateTime());
                    relation.setAddUser(userTask.getUpdateUser());
                    relation.setUpdateUser(userTask.getUpdateUser());
                    String userCode = receiverCode;
                    List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(receiverCode).getData();
                    DepartmentTreeBean departmentTreeBean = (DepartmentTreeBean) util.corp(userCode).getData();
                    relation.setCorpCode(departmentTreeBean == null ? null : departmentTreeBean.getDepartmentCode());
                    relation.setReceiverDepartmentCode(deptBeanList.get(0).getCode());
                    //查找接收人的邮件和电话号码
                    List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(receiverCode, null).getData();
                    if (null != staffBeanList && staffBeanList.size() > 0) {
                        if (!emailList.contains(staffBeanList.get(0).getEmail())) {
                            emailList.add(staffBeanList.get(0).getEmail());
                        }
                        if (!phoneList.contains(staffBeanList.get(0).getMobile())) {
                            phoneList.add(staffBeanList.get(0).getMobile());
                        }
                    }
                    relationList.add(relation);
                    //构造发送消息给任务接收人
                    Message message = new Message();
                    message.setId(DefaultIdGenerator.getInstance().generateLongId());
                    message.setReceiverCode(receiverCode.split("_")[0]);
                    message.setIsRead(0);
                    message.setAddUser(userTask.getUpdateUser());
                    message.setAddTime(userTask.getUpdateTime());
                    message.setUpdateUser(userTask.getUpdateUser());
                    message.setUpdateTime(userTask.getUpdateTime());
                    message.setTitle("您有一条新消息，请注意查收");
                    message.setContent(userTask.getInitiatorName() + "向你发布了一项任务，请注意查收");
                    message.setIsRemove(0);
                    messageList.add(message);
                }
                //给抄送人默认关注此任务
                List<UserTaskFollow> followList = new ArrayList<>();
                if (null != copyList && copyList.size() > 0) {
                    for (String copyCode : copyList) {
                        String code = copyCode.split("_")[0];
                        UserTaskFollow follow = new UserTaskFollow();
                        follow.setId(DefaultIdGenerator.getInstance().generateLongId());
                        follow.setFollowerCode(code);
                        follow.setFollowState(0);
                        follow.setCreateTime(userTask.getUpdateTime());
                        follow.setTaskId(userTask.getId());
                        followList.add(follow);
                    }
                }
                if (null != relationList && relationList.size() > 0) {
                    factory.getMapper(TaskUserRelationMapper.class).batchInsert(relationList);
                }
                if (null != followList && followList.size() > 0) {
                    factory.getMapper(UserTaskFollowMapper.class).batchInsertFollow(followList);
                }
                //发送消息通知任务接收人
                if (null != messageList && messageList.size() > 0) {
                    messageMapper.batchInsert(messageList);
                }
                //发送短信通知
                if (null != phoneList && phoneList.size() > 0) {
                    String content = "安全项目，新增任务通知：任务名称为“" + userTask.getTaskName() + "”;任务描述为：“" + userTask.getTaskDesc() + "”。";
                    for (String phone : phoneList) {
                        logger.info(phone);
                        if (null != phone) {
                            try {
                                SendMsg.sendSMS(phone, content);
                            } catch (Exception e) {
                                if (e.getMessage().equals("手机号码错误")) {
                                    msg.setDescription(e.getMessage());
                                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                                    return msg;
                                }
                            }
                        }

                    }
                }
                //发送邮件
                if (null != emailList && emailList.size() > 0) {
                    String text = userTask.getTaskDesc();
                    String subject = "安全项目，新增任务通知：任务名称：“" + userTask.getTaskName() + "”";
                    SendEmail.complexMailSend(emailList, text, subject, null, inputStreams);
                }
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(operatorType==0?"保存成功":"任务下发成功");
            msg.setData(value);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (keepAttsList != null && keepAttsList.size() > 0) {
                List<String> realKeep = new ArrayList<>();
                if (StringUtils.isNotEmpty(keepAttAddress)) {
                    realKeep = Arrays.asList(keepAttAddress.split("[,，]"));
                }
                for (String att : keepAttsList) {
                    if (!realKeep.contains(att)) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
            }
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.TASK_EMPTY_DEL_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_DEL_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            UserTask task = query(id).getData();
            if (null == task) {
                msg.setCode(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getDescription());
                return msg;
            }
            List<String> delAttList = new ArrayList<>();
            if (StringUtils.isNotEmpty(task.getTaskFile())) {
                delAttList = JSONObject.parseArray(task.getTaskFile(), String.class);
            }
            Integer value = factory.getMapper(UserTaskMapper.class).delete(id);
            if (value > 0) {
                if (null != delAttList && delAttList.size() > 0) {
                    for (String att : delAttList) {
                        clientWrapper.deleteFile(att);
                    }
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除用户任务成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除用户任务失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<UserTask> query(String id) {
        MessageBean<UserTask> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.TASK_EMPTY_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_TASKDESCRIPTION.getDescription());
                return msg;
            }
            UserTask userTask = factory.getMapper(UserTaskMapper.class).queryOne(id);
            // getNames(userTask);
            msg.setCode(0);
            msg.setDescription("获取用户任务详情成功");
            msg.setData(userTask);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<UserTask>> queryForInitiator(String initiatorCode, String taskName, Date deadline, Integer start, Integer rows,String keyword) {
        MessageBean<DataBean<UserTask>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            UserTaskMapper taskMapper = factory.getMapper(UserTaskMapper.class);
            List<UserTask> taskList = taskMapper.queryForInitiator(initiatorCode, taskName, deadline, start, rows,keyword);
            Integer totalNumber = taskMapper.countForInitiator(initiatorCode, taskName, deadline,keyword);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            //taskList.forEach(item -> getNames(item));
            DataBean<UserTask> dataBean = new DataBean<>();
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setList(taskList);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取用户任务列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<UserTask>> queryForReceiver(String userCode, Integer state, String taskName, Date deadline, Integer start, Integer rows,String keyword) {
        MessageBean<DataBean<UserTask>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            UserTaskMapper taskMapper = factory.getMapper(UserTaskMapper.class);
            List<UserTask> taskList = taskMapper.queryForReceiver(userCode, state, taskName, deadline, start, rows,keyword);
            Integer totalNumber = taskMapper.countForReceiver(userCode, state, taskName, deadline,keyword);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            //taskList.forEach(item -> getNames(item));
            DataBean<UserTask> dataBean = new DataBean<>();
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setList(taskList);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取用户任务列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<UserTask>> queryAllByCondition(String taskName, Date deadline, String receiverCode, Integer start, Integer rows) {
        MessageBean<DataBean<UserTask>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            UserTaskMapper taskMapper = factory.getMapper(UserTaskMapper.class);
            List<UserTask> taskList = taskMapper.queryAllByCondition(taskName, deadline, receiverCode, start, rows);
            Integer totalNumber = taskMapper.countAllByCondition(taskName, deadline, receiverCode);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            // taskList.forEach(item -> getNames(item));
            DataBean<UserTask> dataBean = new DataBean<>();
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setList(taskList);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取用户任务列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> saveUserTaskResult(StaffBean user,
                                                   UserTaskResult result,
                                                   MultipartFile[] files,
                                                   String keepAttAddress,
                                                   String delAttAddress,
                                                   List<CustomFormData> beanList,
                                                   String tbaleCode,
                                                   String approver,String title,String description) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        List<String> keepList = new ArrayList<>();
        try {
            if (StringUtils.isNotEmpty(keepAttAddress)) {
                String[] keepArrays = keepAttAddress.split("[,，]");
                for (String att : keepArrays) {
                    keepList.add(att);
                }
            }
            UserTaskResultMapper resultMapper = factory.getMapper(UserTaskResultMapper.class);
            if (StringUtils.isEmpty(result.getUserTaskId())) {
                msg.setCode(BusinessCode.TASKRESULT_EMPTY_TASKID.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EMPTY_TASKID.getDescription());
                return msg;
            }
            if (null == result.getIsDraft()) {
                msg.setCode(BusinessCode.TASKRESULT_EMPTY_ISDRAFT.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EMPTY_ISDRAFT.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(result.getExecutorCode())) {
                msg.setCode(BusinessCode.TASKRESULT_EXCUTORCODE_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EXCUTORCODE_NOT_FOUND.getDescription());
                return msg;
            }
            //判断填写任务结果的任务是否存在
            UserTask task = query(result.getUserTaskId()).getData();
            if (null == task) {
                msg.setCode(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getDescription());
                return msg;
            }
            String receiverCode = user.getCode();
            TaskUserRelation relation = factory.getMapper(TaskUserRelationMapper.class).selectOneByTaskIdAndReceiverCode(result.getUserTaskId(), receiverCode);
            //任务属于他人，无法操作
            if (null == relation) {
                msg.setCode(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getDescription());
                return msg;
            }
            Integer value = 0;
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                }
            }
            if (StringUtils.isEmpty(result.getId())) {
                //根据任务id去判断是否不存在对应的任务结果
                UserTaskResult entity = resultMapper.queryOne(relation.getTaskResultId());
                if (StringUtils.isEmpty(relation.getTaskResultId()) && entity == null) {
                    //新增操作
                    result.setAddUser(result.getUpdateUser());
                    result.setAddTime(result.getUpdateTime());
                    result.setId(DefaultIdGenerator.getInstance().generateLongId());
                    if (null != keepList && keepList.size() > 0) {
                        result.setResultFile(new Gson().toJson(keepList));
                    }
                    resultMapper.insert(result);
                } else {
                    result.setId(entity.getId());
                    if (entity.getIsDraft() == 1) {
                        msg.setCode(BusinessCode.TASKRESULT_IS_COMMITED.getCode());
                        msg.setDescription(BusinessCode.TASKRESULT_IS_COMMITED.getDescription());
                        return msg;
                    }
                    if (null != keepList && keepList.size() > 0) {
                        result.setResultFile(new Gson().toJson(keepList));
                    }
                    resultMapper.update(result);
                    if (StringUtils.isNotEmpty(delAttAddress)) {
                        String[] delAttArray = delAttAddress.split("[,，]");
                        for (String att : delAttArray) {
                            clientWrapper.deleteFile(att.split("#")[0]);
                        }
                    }
                }


                // 新增任务结果操作完成后，将自定义表单数据写入数据库
                if (null != beanList && beanList.size() > 0) {
                    Date date = new Date();
                    for (CustomFormData customFormData : beanList) {
                        if (StringUtils.isEmpty(customFormData.getId())) {
                            customFormData.setId(DefaultIdGenerator.getInstance().generateLongId());
                        }
                        customFormData.setAddUser(user.getCode());
                        customFormData.setAddUserName(user.getName());
                        customFormData.setAddTime(date);
                        customFormData.setUpdateTime(date);
                        customFormData.setUpdateUser(user.getCode());
                        customFormData.setUpdateUserName(user.getName());
                    }
                    factory.getMapper(CustomFormDataMapper.class).batchInsert(beanList);
                }


            } else {
                //判断要修改的任务结果是否存在且未提交
                UserTaskResult entity = resultMapper.queryOne(result.getId());
                if (entity == null) {
                    msg.setCode(BusinessCode.TASKRESULT_TASKRESULT_NOT_FOUND.getCode());
                    msg.setDescription(BusinessCode.TASKRESULT_TASKRESULT_NOT_FOUND.getDescription());
                    return msg;
                }
                if (entity.getIsDraft() == 1) {
                    msg.setCode(BusinessCode.TASKRESULT_IS_COMMITED.getCode());
                    msg.setDescription(BusinessCode.TASKRESULT_IS_COMMITED.getDescription());
                    return msg;
                }
                if (null != keepList && keepList.size() > 0) {
                    result.setResultFile(new Gson().toJson(keepList));
                }
                resultMapper.update(result);
                if (StringUtils.isNotEmpty(delAttAddress)) {
                    String[] delAttArray = delAttAddress.split("[,，]");
                    for (String att : delAttArray) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
            }


            // 修改任务结果完成后，更新自定义表单数据。
            // 先获取当前执行人的历史表单数据
            List<CustomFormData> dataList = factory.getMapper(CustomFormDataMapper.class).queryDataByCondition(tbaleCode, result.getUserTaskId(), user.getCode());
            //再将改后的数据插入数据库
            if (null != beanList && beanList.size() > 0) {
                List<CustomFormData> addList = new ArrayList<>();
                List<CustomFormData> updateList = new ArrayList<>();
                List<CustomFormData> deleteList = new ArrayList<>();
                Date date = new Date();
                for (CustomFormData customFormData : beanList) {
                    if (StringUtils.isEmpty(customFormData.getId())) {
                        customFormData.setId(DefaultIdGenerator.getInstance().generateLongId());
                        customFormData.setAddUser(user.getCode());
                        customFormData.setAddUserName(user.getName());
                        customFormData.setAddTime(date);
                        customFormData.setUpdateTime(date);
                        customFormData.setUpdateUser(user.getCode());
                        customFormData.setUpdateUserName(user.getName());
                        addList.add(customFormData);
                    } else {
                        customFormData.setUpdateTime(date);
                        customFormData.setUpdateUser(user.getCode());
                        customFormData.setUpdateUserName(user.getName());
                        updateList.add(customFormData);
                    }
                }
                if (addList.size() > 0) {
                    factory.getMapper(CustomFormDataMapper.class).batchInsert(addList);
                }
                if (updateList.size() > 0) {
                    List<String> collect = updateList.stream().map(customFormData -> customFormData.getId()).collect(Collectors.toList());
                    if (null != dataList && dataList.size() > 0) {
                        for (CustomFormData customFormData : dataList) {
                            if (!collect.contains(customFormData.getId())) {
                                deleteList.add(customFormData);
                            }
                        }
                    }
                    factory.getMapper(CustomFormDataMapper.class).batchUpdate(updateList);
                    if (deleteList.size() > 0) {
                        factory.getMapper(CustomFormDataMapper.class).batchDelete(deleteList.stream().map(customFormData -> customFormData.getId()).collect(Collectors.toList()));
                    }
                } else {
                    if (null != dataList && dataList.size() > 0) {
                        factory.getMapper(CustomFormDataMapper.class).batchDelete(dataList.stream().map(customFormData -> customFormData.getId()).collect(Collectors.toList()));
                    }
                }
            } else {
                if (null != dataList && dataList.size() > 0) {
                    factory.getMapper(CustomFormDataMapper.class).batchDelete(dataList.stream().map(customFormData -> customFormData.getId()).collect(Collectors.toList()));
                }
            }


            //根据任务结果是否提交，是否发送信息给审批人
            if (result.getIsDraft() == 1) {
                //todo  确认提交之后，是否选择审批人 如果选择了审批人 则默认状态是未完成
                if (StringUtils.isNotEmpty(approver)) {
                    //如果有提交人选中
                    if (StringUtils.isEmpty(title)||StringUtils.isEmpty(description)) {
                        msg.setCode(BusinessCode.DATA_REQUERED_MISSS.getCode());
                        msg.setDescription(BusinessCode.DATA_REQUERED_MISSS.getDescription());
                        return  msg;
                    }
                    com.koron.web.org.bean.StaffBean staffBean = factory.getMapper(StaffMapper.class).queryForCode(relation.getReceiverCode());
                    if (!initFlow(approver,relation,user,title,description,staffBean.getName())) {
                        factory.close(false);
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("提交失败，原因是无法启动流程");
                        return msg;
                    }

                }

                relation.setTaskResultId(result.getId());
                if (StringUtils.isNotEmpty(approver)) {
                    //有设置审核人 初始未完成 待审核
                    //isFinish 0-未完成 1-已完成 2-待审核
                    relation.setIsFinish(3);
                    relation.setState(0);
                } else {
                    //确认提交，发送消息通知审批人对任务结果进行确认
                    insertMsg(task,result,factory,1);
                    //已完成，审批完成
                    relation.setIsFinish(1);
                    relation.setIsFinish(1);
                }
                factory.getMapper(TaskUserRelationMapper.class).update(relation);
                //第一次任务执行人提交任务，将任务的状态修改为进行中
                if(task.getState()==0){
                    task.setState(1);
                    factory.getMapper(UserTaskMapper.class).update(task);
                }
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("保存任务结果成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (keepList != null && keepList.size() > 0) {
                List<String> realKeep = new ArrayList<>();
                if (StringUtils.isNotEmpty(keepAttAddress)) {
                    realKeep = Arrays.asList(keepAttAddress.split("[,，]"));
                }
                for (String att : keepList) {
                    if (!realKeep.contains(att)) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
            }
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    /**
     * 新增消息
     * @param state 1-确定 0-取消
     */
    private void insertMsg(UserTask task,
                           UserTaskResult result,
                           SessionFactory factory,
                           Integer state) throws Exception {
        MessageMapper messageMapper = factory.getMapper(MessageMapper.class);
        Message message = new Message();
        Date date = new Date();
        message.setId(DefaultIdGenerator.getInstance().generateLongId());
        message.setReceiverCode(task.getInitiatorCode());
        message.setIsRead(0);
        message.setAddUser(result.getUpdateUser());
        message.setAddTime(date);
        message.setUpdateUser(result.getUpdateUser());
        message.setUpdateTime(date);
        message.setTitle("您有一条新消息，请注意查收");
        String contentAp = 1==state?"已经完成了，请对任务结果进行确认":"这项任务已被取消";
        message.setContent("您发布任务名称为:" + task.getTaskName() + "任务执行人" + task.getReceiverName() + contentAp);
        message.setIsRemove(0);
        messageMapper.insert(message);
    }


    /**
     * 初始化审批流
     * @param approver
     * @param relation
     * @param user
     * @param title
     * @param description
     * @param name
     * @return
     * @throws Exception
     */
    private boolean initFlow(String approver,
                             TaskUserRelation relation,
                             StaffBean user,
                             String title,
                             String description, String name) throws Exception {

        Audit audit = new Audit();
        audit.setTitle(title);
        //提交审批计划流程
        //c70a8991c1494d59ba351388f2e07147
        Date date=new Date();
        audit.setAddUser(name);
        audit.setAddTime(date);
        audit.setUpdateUser(relation.getUpdateUser());
        audit.setUpdateTime(date);
        audit.setFlowType(1);
        audit.setFlowName(BusinessCode.USER_TASK.getDescription());
        audit.setOperation(1);
        audit.setTarget(UserTaskServiceImpl.class.getName());
        audit.setCorpCode(user.getDepartmentCode());
        audit.setBusinessIds(relation.getTaskId());
        audit.setInitiatorCode(relation.getReceiverCode());
        audit.setDescription(description);
        audit.setState(1);
        audit.setTemplateKey(userTaskTempKey);
        audit.setSetCode(userTaskSetCode);
        audit.setInitiatorAccount(user.getUserid());
        audit.setId(DefaultIdGenerator.getInstance().generateLongId());
        Map<String, Object> businessMap = new HashMap<>();
        businessMap.put("approveUserId", approver);
        return flowManagement.initFlow(user, audit, businessMap);
    }

    @Override
    public MessageBean<List<UserTaskResult>> queryUserTaskResultByTaskId(StaffBean user, String taskId) {
        MessageBean<List<UserTaskResult>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(taskId)) {
                msg.setCode(BusinessCode.TASKRESULT_EMPTY_TASKID.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EMPTY_TASKID.getDescription());
                return msg;
            }
            List<UserTaskResult> list = factory.getMapper(UserTaskResultMapper.class).queryResultListByUserTaskId(taskId);
//            UserTask task = factory.getMapper(UserTaskMapper.class).queryOne(taskId);
//            List<UserTaskResult> realtList = new ArrayList<>();
//            if (null != task) {
//                if (user.getCode().equals(task.getInitiatorCode())) {
//                    realtList.addAll(list);
//                } else {
//                    for (UserTaskResult result : list) {
//                        if (result.getExecutorCode().equals(user.getCode())) {
//                            realtList.add(result);
//                        }
//                    }
//                }
//            } else {
//                realtList.addAll(list);
//            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询成功");
            msg.setData(list);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<UserTaskResult> queryResultByUserTaskIdAndExecutorCode(StaffBean user, String taskId) {
        MessageBean<UserTaskResult> msg=MessageBean.create(BusinessCode.SUCCESS.getCode(),BusinessCode.SUCCESS.getDescription(),UserTaskResult.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(taskId)) {
                msg.setCode(BusinessCode.TASKRESULT_EMPTY_TASKID.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EMPTY_TASKID.getDescription());
                return msg;
            }
            UserTaskResult userTaskResult = factory.getMapper(UserTaskResultMapper.class).queryResultByUserTaskIdAndExecutorCode(taskId,user.getCode());
            msg.setData(userTaskResult);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> confirmUserTaskResult(UserTaskResult result) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(result.getApproverCode())) {
                msg.setCode(BusinessCode.TASKRESULT_EMPTY_APPROVERCODE.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EMPTY_APPROVERCODE.getDescription());
                return msg;
            }
            UserTaskResultMapper resultMapper = factory.getMapper(UserTaskResultMapper.class);
            UserTaskResult en = resultMapper.queryOne(result.getId());
            if (null == en) {
                msg.setCode(BusinessCode.TASKRESULT_TASK_RESULT_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_TASK_RESULT_NOT_FOUND.getDescription());
                return msg;
            }
            if (null == result.getIsPass()) {
                msg.setCode(BusinessCode.TASKRESULT_EMPTY_ISPASS.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_EMPTY_ISPASS.getDescription());
                return msg;
            }
            if (0 != result.getIsPass() && 1 != result.getIsPass()) {
                msg.setCode(BusinessCode.TASKRESULT_ILEAGEL_ISPASS.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_ILEAGEL_ISPASS.getDescription());
                return msg;
            }
            UserTask task = query(en.getUserTaskId()).getData();
            if (!task.getInitiatorCode().equals(result.getApproverCode())) {
                msg.setCode(BusinessCode.TASKRESULT_APPROVERCODE_NOT_AGREEMENT.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_APPROVERCODE_NOT_AGREEMENT.getDescription());
                return msg;
            }
            String receiverCode = en.getExecutorCode();
            TaskUserRelation relation = factory.getMapper(TaskUserRelationMapper.class).selectOneByTaskIdAndReceiverCode(en.getUserTaskId(), receiverCode);
            //任务属于他人，无法操作
            if (null == relation) {
                msg.setCode(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKRESULT_TASK_NOT_FOUND.getDescription());
                return msg;
            }
            Message message = null;
            if (0 == result.getIsPass()) {
                //不通过
                Date date = new Date();
                result.setIsDraft(0);
                message = new Message();
                message.setId(DefaultIdGenerator.getInstance().generateLongId());
                message.setReceiverCode(task.getInitiatorCode());
                message.setIsRead(0);
                message.setAddUser(task.getUpdateUser());
                message.setAddTime(date);
                message.setUpdateUser(task.getUpdateUser());
                message.setUpdateTime(date);
                message.setIsRemove(0);
                message.setTitle("您有一条新消息，请注意查收");
                message.setContent("您提交的任务名称为:" + task.getTaskName() +
                        "的任务结果没有通过审批，要求重新执行该任务");
                relation.setIsFinish(0);
            }else{
                relation.setTaskResultId(result.getId());
                relation.setIsFinish(2);
                relation.setUpdateTime(new Date());
            }
            resultMapper.update(result);
            if (null != message) {
                factory.getMapper(MessageMapper.class).insert(message);
            }
            factory.getMapper(TaskUserRelationMapper.class).update(relation);
            //去查询该任务指派的执行人是否都已经完成任务，若执行人全部完成任务，
            // 更新指派任务的状态为已完成，择无法进行处理操作
            List<UserTaskResult> resultList = factory.getMapper(UserTaskResultMapper.class).queryResultListByUserTaskId(task.getId());
            List<String> receviceList = JSONObject.parseArray(task.getReceiverCode(), String.class);
            if (null != resultList && resultList.size() > 0) {
                Integer count = 0;
                for (UserTaskResult result1 : resultList) {
                    if (null!=result1.getIsPass()&&result1.getIsPass() == 1)
                        count++;
                }
                //完成的任务数和已提交任务比较以及完成任务数与任务下发接收人的个数相比
                if (count == resultList.size()&&count==receviceList.size()) {
                    task.setState(2);
                    factory.getMapper(UserTaskMapper.class).update(task);
                }

            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("确认结果成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> insetUserTaskFollow(UserTaskFollow taskFollow) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(taskFollow.getFollowerCode())) {
                msg.setCode(BusinessCode.TASKFOLLOW_EMPTY_FOLLOWCODE.getCode());
                msg.setDescription(BusinessCode.TASKFOLLOW_EMPTY_FOLLOWCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(taskFollow.getTaskId())) {
                msg.setCode(BusinessCode.TASKFOLLOW_EMPTY_TASKID.getCode());
                msg.setDescription(BusinessCode.TASKFOLLOW_EMPTY_TASKID.getDescription());
                return msg;
            }
            Port port = getPort();
            List<StaffBean> staffBeanList = port.staff(taskFollow.getFollowerCode(), null).getData();
            if (staffBeanList == null || staffBeanList.size() <= 0) {
                msg.setCode(BusinessCode.TASKFOLLOW_FOLLOW_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKFOLLOW_FOLLOW_NOT_FOUND.getDescription());
                return msg;
            }
            UserTask task = query(taskFollow.getTaskId()).getData();
            if (null == task) {
                msg.setCode(BusinessCode.TASKFOLLOW_TASK_NOT_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKFOLLOW_TASK_NOT_FOUND.getDescription());
                return msg;
            }
            List<UserTaskFollow> followList = factory.getMapper(UserTaskFollowMapper.class).queryByFollewCodeAndTaskId(taskFollow.getFollowerCode(),
                    taskFollow.getTaskId());
            if (followList != null && followList.size() > 0) {
                msg.setCode(BusinessCode.TASKFOLLOW_TASK_IS_FOUND.getCode());
                msg.setDescription(BusinessCode.TASKFOLLOW_TASK_IS_FOUND.getDescription());
                return msg;
            }
            taskFollow.setCreateTime(new Date());
            taskFollow.setFollowState(0);
            taskFollow.setId(DefaultIdGenerator.getInstance().generateLongId());
            Integer value = factory.getMapper(UserTaskFollowMapper.class).insertFollow(taskFollow);
            if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("关注成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("关注失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> batchDeleteTaskFollow(List<String> idList) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.TASK_EMPTY_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.TASK_EMPTY_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(UserTaskFollowMapper.class).deleteFollowBatch(idList);
            if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("取消关注成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("取消关注失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<UserTask>> queryByFollewCode(String followerCode, Integer start, Integer rows, String keyword) {
        MessageBean<DataBean<UserTask>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(followerCode)) {
                msg.setCode(BusinessCode.TASKFOLLOW_EMPTY_FOLLOWCODE.getCode());
                msg.setDescription(BusinessCode.TASKFOLLOW_EMPTY_FOLLOWCODE.getDescription());
                return msg;
            }
            List<UserTask> list = factory.getMapper(UserTaskFollowMapper.class).queryByFollewCode(followerCode, start, rows,keyword);
            Integer totalNumber = factory.getMapper(UserTaskFollowMapper.class).countSumByFollewCode(followerCode,keyword);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            // list.forEach(item -> getNames(item));
            DataBean<UserTask> dataBean = new DataBean<>();
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setList(list);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取关注的列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<UserTask>> indexUnDeal(String userCode, Integer page, Integer pageSize) {
        MessageBean<DataBean<UserTask>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<UserTask> list = new ArrayList<>();
            Integer totalNumber = 0;
            UserTaskMapper taskMapper = factory.getMapper(UserTaskMapper.class);
            //查询待办的任务列表
            List<UserTask> receiveTaskList = taskMapper.queryForReceiver(userCode, 0, null, null, null, null,null);
            // Integer receiveTaskTotalNumber = taskMapper.countForReceiver(userCode, null, null, null);
            //查询待处理的任务列表（执行人提交的任务结果）
            List<UserTask> undealTaskList = taskMapper.queryUnDealTask(userCode);
            // Integer undealTaskTotalNumber=taskMapper.countUnDealTask(userCode);
            List<String> idList = new ArrayList<>();
            //将这2个合并成一个列表，注意去重
            if (null != receiveTaskList && receiveTaskList.size() > 0) {
                list.addAll(receiveTaskList);
                idList.addAll(receiveTaskList.stream().map(UserTask::getId).collect(Collectors.toList()));
                if (null != undealTaskList && undealTaskList.size() > 0) {
                    for (UserTask task : undealTaskList) {
                        if (!idList.contains(task.getId())) {
                            list.add(task);
                        }
                    }
                }
            } else {
                if (null != undealTaskList && undealTaskList.size() > 0) {
                    list.addAll(undealTaskList);
                }
            }
            totalNumber = list.size();
            //处理分页问题
            Integer start = 0, end = 0, totalPage = 1;
            if (page != null && page >= 1 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
                end = start + pageSize;
                totalPage = totalNumber > pageSize ? totalNumber % pageSize == 0 ? totalNumber / pageSize : totalNumber / pageSize + 1 : 1;
            }
            if (end > totalNumber) {
                end = totalNumber;
            }
            if (start > end) {
                start = end;
            }
            list.subList(start, end).forEach(item -> getNames(item));
            DataBean<UserTask> dataBean = new DataBean<>();
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setList(list.subList(start, end));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(dataBean);
            return msg;
        }
    }

    private void getNames(UserTask task) {
        if (null != task) {
            if (StringUtils.isNotEmpty(task.getReceiverCode())) {
                Port port = getPort();
                List<String> codeList = JSONObject.parseArray(task.getReceiverCode(), String.class);
                List<String> nameList = new ArrayList<>();
                for (String code : codeList) {
                    String userCode = code.split("_")[0];
                    List<StaffBean> staffBeanList = port.staff(userCode, null).getData();
                    List<DeptBean> deptBeanList = port.dept(userCode).getData();
                    if (null != staffBeanList && staffBeanList.size() > 0 && null != deptBeanList && deptBeanList.size() > 0) {
                        String name = staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName();
                        nameList.add(name);
                    }
                }
                task.setReceiverName((nameList == null || nameList.size() <= 0) ? null : new Gson().toJson(nameList));
            }
            if (StringUtils.isNotEmpty(task.getApproverCode())) {
                Port port = getPort();
                List<StaffBean> staffBeanList = port.staff(task.getApproverCode(), null).getData();
                task.setApproverName((staffBeanList == null || staffBeanList.size() <= 0) ? null : (staffBeanList.get(0).getName()));
            }
        }
    }

    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appId);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }

    //todo 待完成
    @Override
    public void editApproval(Audit audit) {
        try(SessionFactory factory=new SessionFactory()) {
            TaskUserRelationMapper mapper = factory.getMapper(TaskUserRelationMapper.class);
            UserTaskMapper userTaskMapper = factory.getMapper(UserTaskMapper.class);
            UserTaskResultMapper resultMapper = factory.getMapper(UserTaskResultMapper.class);
            TaskUserRelation one = mapper.queryOne(audit.getBusinessIds());
            if (one!=null) {
                one.setState(1);
                one.setIsFinish(1);
                UserTask userTask = userTaskMapper.queryOne(one.getTaskId());
                UserTaskResult userTaskResult = resultMapper.queryOne(one.getTaskResultId());
                //审批后新增消息
                insertMsg(userTask,userTaskResult,factory,1);
                mapper.update(one);
            }
        } catch (Exception e){
            logger.error(e.getMessage(),e);
        }

    }

    @Override
    public void discardApproval(Audit audit) {
        try(SessionFactory factory=new SessionFactory()) {
            TaskUserRelationMapper mapper = factory.getMapper(TaskUserRelationMapper.class);
            TaskUserRelation one = mapper.queryOne(audit.getBusinessIds());
            if (one!=null) {
                one.setState(0);
                one.setIsFinish(0);
                mapper.update(one);
            }
        } catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void processDiscard(Audit audit) {

    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
